//
//  UITextView+Emotion.swift
//  AnimotionKeyboard
//
//  Created by xxy on 16/6/3.
//  Copyright © 2016年 xxy. All rights reserved.
//

import UIKit
extension UITextView {
    /// 图片表情完整字符串内容
    var emoticonText: String {
        var strM = String()
        let attrText = attributedText
        attrText.enumerateAttributesInRange(NSRange(location:0, length: attrText.length ),
                                            options: []) { (dict, range, _) in
                                                // - 如果字典中包含 NSAttachment 说明是图片
                                                // - 否则是字符串，可以通过 range 获得
                                                if  let  attachment = dict["NSAttachment"] as? EmotionTextAttachment {
                                                  strM += attachment.chs ?? ""
                                                }else {
                                                    //截取普通字符串
                                                    let str = (attrText.string as NSString).substringWithRange(range)
                                                    strM += str
                                                }
        }
       return strM   
        
}
    
    
    
    
    /// 插入表情
     /// - parameter em: 表情符号
    func insertEmition(emotion: Emotion){
        //1:是否是空白的
        if emotion.isEmpty {
            
            return
        }
        //2:删除按钮
        if  emotion.isRemoved {
            deleteBackward()
            return
        }
        //3:emoji
        if  let emoji = emotion.emoji {
            
            replaceRange(selectedTextRange!, withText: emoji)
            return
        }
        //4:其他表情
        insetImageEmotion(emotion)
        
    }
    
    private func insetImageEmotion(emotion: Emotion) {
        //1:创建图片属性文本
        let imageAtt = EmotionTextAttachment.imageText(emotion, font: font!)
        //2>获取textView的属性文本
        let textAtt = NSMutableAttributedString(attributedString: attributedText)
        //替换属性内容
        textAtt.replaceCharactersInRange(selectedRange, withAttributedString: imageAtt)
        //记录光标的位置
        let range = selectedRange
        
        attributedText = textAtt
        //恢复光标的位置
        selectedRange = NSRange(location: range.location + 1, length: 0)
    }
}